<template>
  <ga-drawer class="topo-node-drawer" width="75%" :visible="visible" @cancel="() => emits('on-close')">

    <template #header>
      <div class="flex-spb-center" style="width: 100%;">
        <div>
          <span @click="() => emits('on-close')"><icon-close /></span>
          <span>
            <span>{{ edgeInfo?.source?.substring(edgeInfo.source.lastIndexOf('#') + 1) }}</span>
            <span>&nbsp;-&gt;&nbsp;</span>
            <span>{{ edgeInfo?.target?.substring(edgeInfo.target.lastIndexOf('#') + 1) }}</span>
          </span>
        </div>
        <ga-space>
          <ga-button @click="refresh"><template #icon>
              <icon-refresh />
            </template></ga-button>
        </ga-space>
      </div>
    </template>
    <ga-alert type="warning" class="mb12" v-show="hasException">{{ exceptionInfo.exceptionMsg?.join("；") }}</ga-alert>
    <div class='mb10 flex'>
      <!-- <FieldInfo :list="firstInfoList" :data="avgRespTimeData" mode='card'></FieldInfo> -->
      <div v-for="item in firstInfoList" class="card" :key="item.key" :style="item.style || {}">
        <div class="card-title" :title="item.title">{{ item.title }}:</div>
        <div class="card-value">
          <span>{{ formatUnit(fieldInfo[item.dataIndex], item.unit) }}</span>
          <RateInfo title='同比' :value="fieldInfo[item.yearIndex]" style="margin: 0 8px " />
          <RateInfo title='环比' :value="fieldInfo[item.monthIndex]" />
        </div>

      </div>
    </div>

    <ga-tabs type="card-gutter">
      <ga-tab-pane v-for="item in tabsList" :key="item.key" :title="item.label">
        <component :is="item.name" v-bind="item.props" v-on="item.events || {}" :tab="activeTab" pageType="edge"
          :visible="visible" :node="edgeInfo" :queryTime="selectTime" :type="drawerType" @on-filter="filterUrl" />
      </ga-tab-pane>
    </ga-tabs>
  </ga-drawer>
</template>
<script>
export default {
  name: 'TopoEdgeDetail'
}
</script>
<script setup>
import { computed, reactive, ref, toRefs, watch } from 'vue';
// import { useRoute } from 'vue-router';

import dayjs from 'dayjs';
import { cloneDeep, isEmpty } from 'lodash'
import RateInfo from '@/components/RateInfo'
import RequestTab from '../topoNodeDetail/components/RequestTab';
import Network from "./NetworkTab";
import { formatUnit } from '@/utils/format'
import { handleWorkloadKey } from '@/utils';
import { getExceptionInfo } from './service';
import { getAvgRespTime } from '@/api/topoNodeDetail';
import { bus } from '@/utils/eventBus';
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  edgeInfo: {
    type: Object,
    default: () => ({})
  },

  drawerType: {
    type: String,
    default: 'workload'
  },

  defaultActiveKey: {
    type: String,
    default: 'net'
  },
  queryTime: {
    type: Object,
    default: () => ({})
  }
})
const emits = defineEmits(['on-close'])
// const { nodeInfo, drawerType, srcNodes } = toRefs(props)
// console.log(nodeInfo, 'nodeInfo');
const avgRespTimeData = ref({})
const p95ResponseTimeData = ref({})
const firstInfoList = [
  {
    title: '请求量',
    dataIndex: 'requestTotal',
    unit: 'count',
    yearIndex: 'requestTotalDodRate',
    monthIndex: 'requestTotalRingRate',

  }, {
    title: '错误率',
    dataIndex: 'errorRate',
    unit: '%',
    yearIndex: 'errorRateDodRate',
    monthIndex: 'errorRateRingRate',
    // render: (text, data) => <div>
    //     <span>{formatUnit(text, '%')}</span>
    //     <RateInfo title='同比' value={data.errorRateDodRate} style={{ margin: '0 8px' }} />
    //     <RateInfo title='环比' value={data.errorRateRingRate} />
    // </div>
  }, {
    title: '平均响应时间',
    dataIndex: 'responseTime',
    unit: 'ns',
    yearIndex: 'responseTimeDodRate',
    monthIndex: 'responseTimeRingRate',
  }, {
    title: 'P95响应时间',
    dataIndex: 'avgResponseTime',
    unit: 'ns',
    yearIndex: 'avgResponseTimeSameRatio',
    monthIndex: 'avgResponseTimeRingRatio',
  }
];
const pickerValue = reactive([
  dayjs().subtract(12, "hour").valueOf(),
  dayjs().valueOf(),
])
const selectTime = computed(() => {
  const [from, to] = pickerValue

  return {
    from: dayjs(from).format('YYYY-MM-DD HH:mm:ss'),
    to: dayjs(to).format('YYYY-MM-DD HH:mm:ss')
  }
})


const hasException = computed(() => {
  return exceptionInfo.exceptionMsg?.length > 0
})

const activeTab = ref('net')
const url = ref("")
const exceptionInfo = ref({ exceptionMsg: [] })
const fieldInfo = computed(() => {
  console.log({ ...props.edgeInfo, ...avgRespTimeData.value, ...p95ResponseTimeData.value }, 'computed value',p95ResponseTimeData);

  return { ...props.edgeInfo, ...avgRespTimeData.value, ...p95ResponseTimeData.value }
})
// 平均响应时间同环比数据
const getAvgRespTimeData = () => {
  console.log(selectTime, 'selecttIME');

  const { from, to } = selectTime.value
  const {
    masterIp: srcMasterIp,
    namespace: srcNamespace,
    workloadKind: srcWorkloadKind,
    workloadName: srcWorkloadName,
  } = handleWorkloadKey(props.edgeInfo?.srcWorkloadKey || '');
  const {
    masterIp: dstMasterIp,
    namespace: dstNamespace,
    workloadKind: dstWorkloadKind,
    workloadName: dstWorkloadName,
  } = handleWorkloadKey(props.edgeInfo?.dstWorkloadKey || '');
  const params = {
    dstMasterIp: dstMasterIp,
    dstNamespace: dstNamespace,
    dstWorkloadName: dstWorkloadName,
    dstWorkloadKind: dstWorkloadKind,
    from,
    to,
    srcWorkloadList: [{
      masterIp: srcMasterIp,
      namespace: srcNamespace,
      workloadName: srcWorkloadName,
      workloadKind: srcWorkloadKind
    }],
  }
  getAvgRespTime(params).then(res => {
    const { avgResponseTime, avgResponseTimeRingRatio, avgResponseTimeSameRatio, p95ResponseTime,
      p95ResponseTimeRingRatio,
      p95ResponseTimeSameRatio, } = res.data || {};
    avgRespTimeData.value = {
      avgResponseTime: avgResponseTime || null,
      avgResponseTimeRingRatio: avgResponseTimeRingRatio || null,
      avgResponseTimeSameRatio: avgResponseTimeSameRatio || null,
    }
    p95ResponseTimeData.value = {
      p95ResponseTime: p95ResponseTime || null,
      p95ResponseTimeRingRatio: p95ResponseTimeRingRatio || null,
      p95ResponseTimeSameRatio: p95ResponseTimeSameRatio || null,
    }
    console.log(p95ResponseTimeData, 'p95');

    // console.log(avgRespTimeData.value, 'avg value');

  })
}
const refresh = () => {
  // eventProxy.trigger('refresh_chart');
  bus.emit('updateTopoEdgeDetail')
}
const filterUrl = (path) => {
  url.value = path;
  activeTab.value = 'relation';
}
const tabsList = [
  {
    key: 'net',
    label: '网络趋势',
    name: Network,
    props: {
      node: props.edgeInfo,
      visible: props.visible,
      queryTime: props.queryTime,
      pageType: 'edge',
      type: props.drawerType,
      url: url.value
    }
  },
  {
    key: 'relation',
    label: '调用关系',
    name: RequestTab,
    props: {
      node: props.edgeInfo,
      visible: props.visible,
      queryTime: props.queryTime,
      pageType: 'edge',
      type: props.drawerType,
      url: url.value
    }
  }
];
watch(() => props.edgeInfo, (edgeInfo) => {
  if (!isEmpty(edgeInfo)) {
    exceptionInfo.value = getExceptionInfo(edgeInfo)
    getAvgRespTimeData()
  }
})


</script>

<style scoped lang="scss">
.topo-node-drawer {
  .card {
    background-color: rgba(34, 110, 231, 0.06);
    padding: 12px;
    border-radius: 4px;
    flex-basis: 0;
    flex-grow: 1;
    margin: 0 4px;
    overflow: hidden;

    .card-title {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .card-value {
      font-size: 18px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.85);
    }

    &:first-child {
      margin-left: 0;
    }

    &:last-child {
      margin-right: 0;
    }
  }

  :deep(.garco-tabs-type-card-gutter > .garco-tabs-content) {
    border: none;
  }

  :deep(.garco-tabs-nav-tab) {
    background-color: transparent !important;
  }
}
</style>
